import React, { useEffect, useState } from 'react'
import { Table, Tree, Space, Button, Modal, message } from 'antd'
import { DeleteTwoTone, EditTwoTone, ExclamationCircleFilled } from '@ant-design/icons';
import axios from 'axios';
import CreateRole from '../../../components/role/CreateRole';
import EditRole from '../../../components/role/EditRole';

import './RoleList.css'
export default function RoleList() {
    const { confirm } = Modal;
    const [list, setList] = useState([])
    const [isOpen, setIsOpen] = useState(false)
    const [expandedKeys, setExpandedKeys] = useState([]);
    const [checkedKeys, setCheckedKeys] = useState([]);
    const [autoExpandParent, setAutoExpandParent] = useState(true);
    const [treeData, setTreeData] = useState([]);
    const [currentListId, setCurrentListId] = useState()
    const [loding, setLoding] = useState(false)
    const [showCreateRole, setShowCreateRole] = useState(false)
    const [showEditRole, setShowEditRole] = useState(false)

    useEffect(() => {
        setLoding(true)
        axios.get("http://192.168.2.3:3000/roles")
            .then(res => {
                setList(res.data)
                setLoding(false)
            })
        return () => { }
    }, []
    )
    
    useEffect(() => {
        axios.get("http://192.168.2.3:3000/rights?_embed=children")
            .then(res => {
                const handleRes = handleTreeData(res.data)
                console.log(handleRes)
                setTreeData(handleRes)
            })
        return () => { }
    }, [])

    const handleTreeData = (data) => {
        data.forEach((item) => {
            if (item.hasOwnProperty('label')) {
                item.title = item.label;
            }
            if (item.hasOwnProperty('children') && item.children.length > 0) {
                handleTreeData(item.children);
            }
        });
        return data;
    };
    const editClick = (data) => {
        console.log("editClick", data)
        setShowEditRole(true)
        setCurrentListId(data.id)
    };
    const cancleModel = () => {
        setIsOpen(false)
    };
    const okModel = () => {
        console.log("okmodel", checkedKeys)
        //更新数据库
        updateAndGet();
        setIsOpen(false)
        setLoding(true)
    }
    const showDeleteConfirm = (record) => {
        confirm({
            title: '删除',
            icon: <ExclamationCircleFilled />,
            content: '你确定要删除吗？',
            okText: '确定',
            okType: 'danger',
            cancelText: '取消',
            onOk() {
                setLoding(true)
                deleteAndGet(record.id);
                console.log('OK');
            },
            onCancel() {
                console.log('Cancel');
            },
        });
    };

    async function deleteAndGet(id) {

        try {
            await axios.delete(`http://192.168.2.3:3000/roles/${id}`)
                .then(res => {
                    if (res.status === 200) {
                        message.info("删除成功！")
                    } else {
                        message.error("删除失败！")
                    }
                })
            const get = await axios.get("http://192.168.2.3:3000/roles");
            const getRes = get.data;
            console.log("getRes", getRes)
            setList(getRes)
            setLoding(false)
        } catch (error) {
            console.error(error);
        }
    }


    async function updateAndGet() {

        try {
            const update =
                await axios.patch(
                    `http://192.168.2.3:3000/roles/${currentListId}`,
                    { rights: checkedKeys }
                );
            const updateRes = update.data;
            console.log("updateRes", updateRes);
            const get = await axios.get("http://192.168.2.3:3000/roles");
            const getRes = get.data;
            console.log("getRes", getRes)
            setList(getRes)
            setLoding(false)
        } catch (error) {
            console.error(error);
        }
    }


    const columns = [
        {
            title: 'ID',
            dataIndex: 'id',
            key: 'id',
            render: (text) => <a>{text}</a>,
        },
        {
            title: '角色名称',
            dataIndex: 'roleName',
            key: 'roleName',
        },
        {
            title: '角色描述',
            dataIndex: 'description',
            key: 'description',
            render: (text) => (text ? (
                <span className="text-ellipsis" title={text}>
                    {text.length > 10 ? text.slice(0, 10) + '...' : text}
                </span>
            ) : '-')
        },
        {
            title: '操作',
            key: 'action',
            render: (_, record) => (
                <Space size="middle">
                    <Button
                        type='link'
                        danger
                        shape="circle"
                        onClick={() => showDeleteConfirm(record)}
                        icon={<DeleteTwoTone twoToneColor="#eb2f96" />} />
                    <Button
                        type='primary'
                        shape="circle"
                        icon={<EditTwoTone />}
                        onClick={() => editClick(record)}
                    />

                </Space >
            ),
        },
    ];
    const onExpand = (expandedKeysValue) => {
        console.log('onExpand', expandedKeysValue);
        // if not set autoExpandParent to false, if children expanded, parent can not collapse.
        // or, you can remove all expanded children keys.
        setExpandedKeys(expandedKeysValue);
        setAutoExpandParent(false);
    };
    const onCheck = (checkedKeysValue) => {
        console.log('onCheck', checkedKeysValue);
        setCheckedKeys(checkedKeysValue);
    };
    const createClick = () => {
        setShowCreateRole(true);
    }
    return (
        <div>
            <div style={{
                "float": "right",
                "margin": "8px"
            }}>
                <Button
                    type="primary"
                    size='large'
                    onClick={createClick}>
                    新建
                </Button>
            </div>
            <Table
                rowKey={(list) => list.id}
                columns={columns}
                pagination={false}
                dataSource={list}
                loading={loding}
            />
            <Modal
                title="权限配置"
                open={isOpen}
                onCancel={cancleModel}
                onOk={okModel}
                okText="确认"
                cancelText="取消"
                destroyOnClose={true}
            >
                <Tree
                    style={{
                        height: '450px',
                        overflow: 'auto',
                        textAlign: 'center'
                    }}
                    checkable
                    onExpand={onExpand}
                    expandedKeys={expandedKeys}
                    autoExpandParent={autoExpandParent}
                    onCheck={onCheck}
                    checkedKeys={checkedKeys}
                    treeData={treeData}
                />
            </Modal>
            {showCreateRole && <CreateRole
                setLoding={setLoding}
                setList={setList}
                treeData={treeData}
                open={true}
                setShowCreateRole={setShowCreateRole}
            />}

            {showEditRole && <EditRole
                setLoding={setLoding}
                setList={setList}
                treeData={treeData}
                open={true}
                setShowEditRole={setShowEditRole}
                id = {currentListId}
            />}
        </div>
    )
}
